package com.dxy.hms.listener;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.corundumstudio.socketio.SocketIOServer;
import com.dxy.hms.base.AppConstant;
import com.dxy.hms.config.InitInfoProperties;
import com.dxy.hms.model.entity.User;
import com.dxy.hms.mapper.UserMapper;
import com.dxy.hms.utils.MD5Util;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.util.List;

@Slf4j
@Component
@Order(1)
@Data
public class AdminInitHandler implements AppInitHandler {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private InitInfoProperties initInfoProperties;


    @Override
    public void execute() {

        // PS：使用mybatis plus的saveOrUpdate()方法在更新时不会把主键id返回到实体类中

        // 初始化管理员用户
        User adminUserInfo = initInfoProperties.getSuperAdmin();
        String account = adminUserInfo.getAccount();
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getAccount, account));
        if (CollUtil.isEmpty(userList)) {
            String password = MD5Util.getEncryptPassword(frontendEncrypt(adminUserInfo.getPassword()));
            userMapper.insert(new User()
                    .setAccount(account)
                    .setPassword(password)
                    .setType(AppConstant.SUPER_ADMIN_USER_TYPE)
                    .setStatus(AppConstant.USER_ENABLE_STATUS));
        }
    }

    /**
     * 前端加密逻辑
     *
     * @param text
     * @return
     */
    @SneakyThrows
    private static String frontendEncrypt(String text) {
        // 第一次MD5加密
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] firstHash = md.digest(text.getBytes());

        // 将字节数组转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : firstHash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        // 反转字符串
        String reversed = hexString.reverse().toString();

        // 第二次MD5加密
        md.update(reversed.getBytes());
        byte[] secondHash = md.digest();

        // 转换第二次哈希为十六进制字符串
        StringBuilder finalHash = new StringBuilder();
        for (byte b : secondHash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                finalHash.append('0');
            }
            finalHash.append(hex);
        }

        return finalHash.toString();
    }

}
